#include "cpurankitem.h"
#include "qdebug.h"
#include "ui_cpurankitem.h"

#include <QMouseEvent>

CpuRankItem::CpuRankItem(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CpuRankItem)
{
    ui->setupUi(this);

    connect(ui->checkBox, &QCheckBox::stateChanged, this, [=](int state){
        emit switchIdChagned(m_id, state == Qt::CheckState::Checked);
    });
}

CpuRankItem::~CpuRankItem()
{
    delete ui;
}

CpuRankItem *CpuRankItem::fromMap(const QVariantMap &map, CpuRankItem *item)
{
    auto self = item ? item : new CpuRankItem;

    auto id = map.value("id").toString();
    auto pai_ming = map.value("pai_ming").toInt();
    auto ming_cheng = map.value("ming_cheng").toString();
    auto shu_zhi = map.value("shu_zhi").toString();
    auto bai_fen_bi = map.value("bai_fen_bi").toDouble();

    self->setId(id);
    self->setMingCheng(ming_cheng);

    self->ui->cpu_rank_pai_ming->setText(QString::number(pai_ming));
    self->ui->cpu_rank_ming_cheng->setText(ming_cheng);
    self->ui->cpu_rank_shu_zhi->setText(shu_zhi);
    self->ui->cpu_rank_bai_fen_bi->setValue(bai_fen_bi);

    return self;
}

QString CpuRankItem::id() const
{
    return m_id;
}

void CpuRankItem::setId(const QString &newId)
{
    if (m_id == newId)
        return;
    m_id = newId;
    emit idChanged();
}

QString CpuRankItem::mingCheng() const
{
    return m_mingCheng;
}

void CpuRankItem::setMingCheng(const QString &newMingCheng)
{
    if (m_mingCheng == newMingCheng)
        return;
    m_mingCheng = newMingCheng;
    emit mingChengChanged();
}

void CpuRankItem::setSwtiched(bool value)
{
    ui->checkBox->setCheckState(value ? Qt::Checked : Qt::Unchecked);
}

void CpuRankItem::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        qDebug() << "左键点击位置:" << event->pos();
        if (!ui->checkBox->geometry().contains(event->pos())) {
            m_onePos = event->pos();
        }
        // 处理点击逻辑...
    }
    QWidget::mousePressEvent(event); // 调用父类处理
}

void CpuRankItem::mouseReleaseEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        qDebug() << "左键释放位置:" << event->pos();
        if (!ui->checkBox->geometry().contains(event->pos())) {
            if (m_onePos == event->pos()) {
                auto state = ui->checkBox->checkState();
                ui->checkBox->setCheckState(state == Qt::Unchecked ? Qt::Checked : Qt::Unchecked);
            }
        }
    }
    QWidget::mouseReleaseEvent(event);
}
